package chapter11ProducerAndConsumer;

/**
 * 仓库
 * Created by LinGer on 2019/6/19
 */
public class Depot {

    /**
     * 仓库的容量
     */
    private int capacity;

    /**
     * 仓库的现有产品数量
     */
    private int size;

    public Depot(int capacity){
        this.capacity = capacity;
        this.size = 0;
    }

    public synchronized void produce(int val){
        try{
            //left表示想要生产产品的数量，有可能需要生产的数量太多，要多次生产
            int left = val;
            while (left > 0){
                //库存已满时，等待消费者消费
                while (size >= capacity){
                    wait();
                }

                //如果要生产的数量超过了容量，则生产到填满仓库位置
                int increment = (size+left) > capacity ? (capacity-size) : left;
                size += increment;
                left -= increment;
                System.out.println(Thread.currentThread().getName() + " produce: " + val + " --> left=" + left + " ,increment=" + increment + " ,size="+size);
                //通知消费者可以消费了
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public synchronized void consume(int val){
        try{
            //消费者消费的数量，有可能消费数量太大，库存不够，需要多次消费
            int left = val;
            while (left > 0){
                while (size <= 0) {
                    wait();
                }

                int decrease = (size<left) ? size : left;
                size -= decrease;
                left -= decrease;

                System.out.println(Thread.currentThread().getName() + " consume: " + val + " --> left=" + left + " ,decrease=" + decrease + " ,size="+size);
                //通知生产者生产
                notifyAll();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
